/***************************************************************************
[FileName]
-------------------
    begin                : 03.201s1
    copyright            : by kuzkok
    email                : kuzkok@gmail.com

***************************************************************************
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
*   
*   Данная программа является свободным программным обеспечением;         *
*   Вы можете распространять ее и/или модифицировать в соответствии с     *
*   GNU General Public License опубликованной Фондом свободного           *
*   программного обеспечения; используемая версия лицензии - 2 или        *
*   (по вашему выбору) любая более поздняя                                *
***************************************************************************/
#include <QMessageBox>

//#include "qgsdatasourceuri.h"

#include "ListChoose.h"
#include "ui_listchoose.h"
#include "dbconnection.h"
#include "psqlenumdelegate.h"
#include "tunetablemodel.h"
//#include "unique.h"

ListChoose::ListChoose(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ListChoose)
{
    ui->setupUi(this);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);    
    connect(ui->pushButtonSaveEdit, SIGNAL(clicked()), this, SLOT(saveChanges()));    
    connect(ui->pushButtonStartStopEditActivity, SIGNAL(clicked()), this, SLOT(changeEditMode()));
    connect(ui->pushButtonAddRow, SIGNAL(clicked()), this, SLOT(addRow()));
    connect(ui->pushButtonDeleteRow, SIGNAL(clicked()), this, SLOT(removeSelected()));
    connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), ui->buttonBox, SIGNAL(accepted()));
}

ListChoose::~ListChoose()
{
    delete ui;
    delete tableModel;
}

void ListChoose::loadData(QString theTableName, QString where_clause)
{
    //mapCanvas =  unique::inst()->QgisIface()->mapCanvas();
    tableName = theTableName;    
    if (dbconnection::instance()->connected())
    {
        tableModel = new CustomRelationModel(this, dbconnection::instance()->database());
        tableModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
        tableModel->setTable(theTableName);
        tableModel->setFilter(where_clause);
        if(tableModel->select())
        {
            isDirty = false;
            ui->pushButtonAddRow->setEnabled(false);
            ui->pushButtonDeleteRow->setEnabled(false);
            ui->pushButtonSaveEdit->setEnabled(false);
            psqlenumdelegate *delegate = new psqlenumdelegate(theTableName, dbconnection::instance()->database());
            ui->tableView->setModel(tableModel);
            ui->tableView->setItemDelegate(delegate);
            connect(tableModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(dataChanged()));            
            tunetablemodel::tune(tableModel, ui->tableView);
        }
        else
            QMessageBox::information(this, "error", tableModel->lastError().text());
    }
}

void ListChoose::saveChanges()
{
    if(tableModel->submitAll())
    {
        isDirty = false;
    }
    else
        QMessageBox::information(this, "Ошибка", tableModel->lastError().text());
}

void ListChoose::changeEditMode()
{
    if(ui->pushButtonStartStopEditActivity->isChecked())
    {
        ui->tableView->setEditTriggers(QAbstractItemView::DoubleClicked |
                                       QAbstractItemView::EditKeyPressed |
                                       QAbstractItemView::AnyKeyPressed);
        ui->pushButtonAddRow->setEnabled(true);
        ui->pushButtonDeleteRow->setEnabled(true);
        ui->pushButtonSaveEdit->setEnabled(true);
        ui->tableView->setSortingEnabled(false);
    }
    else
    {
        if(isDirty)
        {
            switch(QMessageBox::information(this, "Информация", "Сохранить изменения",
                                        QMessageBox::Yes|QMessageBox::No|QMessageBox::Cancel ))
            {
            case QMessageBox::Yes:
                tableModel->submitAll();
                break;
            case QMessageBox::No:
                tableModel->revertAll();
                break;
            case QMessageBox::Cancel:
                ui->pushButtonStartStopEditActivity->setChecked(true);
                return;
                break;
            default:
                break;
            }
        }
        ui->pushButtonAddRow->setEnabled(false);
        ui->pushButtonDeleteRow->setEnabled(false);
        ui->pushButtonSaveEdit->setEnabled(false);
        ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);        
        ui->tableView->setSortingEnabled(true);
    }
}

void ListChoose::removeSelected()
{
    if(QMessageBox::question(this, "Удаление", "Удалить выделенные строки?", QMessageBox::Yes|QMessageBox::No) ==
       QMessageBox::Yes)
        foreach(QModelIndex idx, ui->tableView->selectionModel()->selectedRows())
                tableModel->removeRow(idx.row());
}

QString ListChoose::selectedID()
{
    QModelIndex idx = ui->tableView->selectionModel()->selectedRows().first();
    QSqlRecord rec = tableModel->record();    
    return tableModel->data(tableModel->index(idx.row(), rec.indexOf("eventid"))).toString();
}
